package com.supreme.commonrocketmq.utils;

import com.alibaba.fastjson.JSONObject;
import com.supreme.common.entityRocketmq.MQLogger;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class RocketmqSendUtils {

    public static MQLogger buildLoggerPayload(JoinPoint joinPoint, HttpServletRequest servletRequest) {
        MQLogger loggerPayload = new MQLogger();

        Signature joinPointSignature = joinPoint.getSignature();
        loggerPayload.setController(joinPointSignature.getDeclaringType().getSimpleName());
        loggerPayload.setMethod(joinPointSignature.getName());

        if (Objects.isNull(servletRequest)) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            if (Objects.nonNull(servletRequestAttributes)) {
                servletRequest = servletRequestAttributes.getRequest();
            }
        }

        if (Objects.nonNull(servletRequest)) {
            loggerPayload.setRequestUrl(servletRequest.getRequestURL().toString());
            loggerPayload.setRequestUri(servletRequest.getRequestURI());
            loggerPayload.setRequestMethod(servletRequest.getMethod());
        }

        return loggerPayload;
    }

    public static <TP> void sendMessage(MQProducer producer, String topic, TP loggerPayload) {
        Message message = new Message();
        message.setTopic(topic);

        byte[] jsonBytes = JSONObject.toJSONBytes(loggerPayload);
        message.setBody(jsonBytes);
        try {
            producer.sendOneway(message);
        } catch (MQClientException | RemotingException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
